package com.zy.je.common.knife4j.config;

import com.github.xiaoymin.knife4j.core.util.AnnotationUtils;
import com.google.common.base.Strings;
import io.swagger.annotations.ApiModel;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.schema.ApiModelTypeNameProvider;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

@Primary
@Component
public class SwaggerApiModelTypeNameProvider extends ApiModelTypeNameProvider {

    private final Map<String, Pair<String, String>> classNames = new ConcurrentHashMap<>();

    @Override
    public String nameFor(Class<?> type) {
        ApiModel annotation = AnnotationUtils.findAnnotation(type, ApiModel.class).orElse(null);

        String defaultTypeName = type.getTypeName().replace(type.getPackageName() + ".", "");

        defaultTypeName = annotation != null ? Optional.ofNullable(Strings.emptyToNull(annotation.value())).orElse(defaultTypeName) : defaultTypeName;

        Pair<String, String> classPackagePair = classNames.get(defaultTypeName);
        if (classPackagePair != null) {
            if (!classPackagePair.getValue().equalsIgnoreCase(type.getPackageName())) {
                defaultTypeName = "_" + defaultTypeName;
            }
        }
        classNames.put(defaultTypeName, Pair.of(type.getTypeName(), type.getPackageName()));

        return defaultTypeName;

    }
}

